// 注册
if(document.getElementById("register")) {
	document.getElementById("register").onclick = function() {
		var form = this.form;
		var array = new Array();
		// 把表单里的数据存到数组里
		for(var i = 0; i < form.length - 1; i++) {
			array[i] = form[i].value;
		}
		var data = "username=" + array[0] + "&email=" + array[1] + "&password=" + array[2] + "&vcode=" + array[3];
		var url = "public/api.web.php/user/register";
		ajax("POST", url, data);
	}
}
// 登录
if(document.getElementById("login")) {
	document.getElementById("login").onclick = function() {
		var form = this.form;
		var array = new Array();
		// 把表单里的数据存到数组里
		for(var i = 0; i < form.length - 1; i++) {
			array[i] = form[i].value;
		}
		var data = "email=" + array[0] + "&password=" + array[1];
		var url = "public/api.web.php/user/login";
		// console.log(array);
		ajax("POST", url, data);
	}
}
// 创建站点
// if(document.getElementById("addweb")) {
// 	document.getElementById("addweb").onclick = function() {

// 	}
// }
/**
 *
 方法说明：ajax封装函数
 *
 @method ajax()
 *
 @param {string}   type   提交的类型
 @param {string}   url    提交到的URL地址
 @param {string}   data   POST提交时带的参数
 *
 @return 
 */
function ajax(type, url, data) {
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.open(type, url);
	if(type == "POST") {
	    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    }
    if(type == "POST") {
	    xmlhttp.send(data);
	}else {
		xmlhttp.send();
	}
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState===4) {
			if (xmlhttp.status===200) {
				var txt = JSON.parse(xmlhttp.responseText);
				console.log(xmlhttp.responseText);
				console.log(txt);
				if(txt.code == 200) {
					if(txt.message == "注册成功") {
						alert(txt.message);
					    window.location.href = "login.html";
				    }else if(txt.message == "登陆成功"){
                        console.log("ok");
                        // console.log(txt.data.token);
                        // console.log(txt.data.user_id);
                        // console.log(txt.data.username);
                        loginOk(txt);
                        window.location.href = "website.html";
				    }
				}else {
					alert(txt.message);
				}
			} else {
				alert("发生错误：" + xmlhttp.status);
			}
		} 
	}
}
// 登陆成功后把返回值存放在sessionStorage
function loginOk(txt) {
	sessionStorage.setItem("token", txt.data.token);
	sessionStorage.setItem("user_id", txt.data.user_id);
	sessionStorage.setItem("username", txt.data.username);
}